﻿using System;
using System.Configuration;
using System.IO;
using System.Text;

namespace HU8.Helpers.Base
{
    /// <summary>
    /// 日志助理
    /// </summary>
    /// Author      Chiron
    public static class LogHelper
    {
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="ex">异常对象</param>
        public static void Append(Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sb.AppendLine(ex.ToString());
            sb.AppendLine(new string('-', 10));

            Save(sb.ToString());
        }

        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="strText">日志内容</param>
        private static void Save(string strText)
        {
            string logFolder = Path.Combine(PathHelper.MapPath(ConfigurationManager.AppSettings["LogDir"] ?? "~/App_Data/Logs"), DateTime.Now.ToString("yyyy MM dd"));

            string logName = DateTime.Now.ToString("HH mm ss fff") + "_" + new Random().Next().ToString() + ".log";
            string logPath = Path.Combine(logFolder, logName);

            try
            {
                if (!Directory.Exists(logFolder)) Directory.CreateDirectory(logFolder);

                using (var sw = File.AppendText(logPath))
                {
                    sw.WriteLine(strText);
                }
            }
            catch { }
        }

    }
}
